package com.guzipi.websocketdemo.bean;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class MyHandlerCopy extends TextWebSocketHandler {


    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketSession> webSocketMap = new ConcurrentHashMap<String,WebSocketSession>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/



    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {


        log.info(message.getPayload());
        String sourceUser=extractUserId(session);
        if(StringUtils.isNotBlank(message.getPayload())){
            try {
                //解析发送的报文
                SocketMessage jsonObject = JSON.parseObject(message.getPayload(), SocketMessage.class);
                //追加发送人(防止串改)

                String toUserId=jsonObject.getDestUserId();
                //传送给对应toUserId用户的websocket
                if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
                    webSocketMap.get(toUserId).sendMessage(new TextMessage(message.getPayload()));
                }else{
                    log.error("请求的userId:"+toUserId+"不在该服务器上");
                    //否则不在这个服务器上，发送到mysql或者redis
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws IOException {
        //super.afterConnectionEstablished(session);

        /**接收userId*/
        String userId="";
        userId= extractUserId(session);
        if(webSocketMap.containsKey(userId)){
             webSocketMap.get(userId).close();//先关闭会话
            webSocketMap.remove(userId);//移除
            //加入set中
        }
        webSocketMap.put(userId,session);
        addOnlineCount();
        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());

        try {
            SocketMessage msg=new SocketMessage();
            msg.setMsgType("ConnectInfo");
            msg.setSrcUserId("WebServer");
            msg.setDestUserId(userId);
            msg.setMsgBody("连接成功");
            String msgStr=JSON.toJSONString(msg);
            sendMessage(session,msgStr);
            //有新用户登陆后把用户列表进行广播
            broadCastUserList();
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }


    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(WebSocketSession session,String message) throws IOException {
        TextMessage txtMsg=new TextMessage(message);
        session.sendMessage(txtMsg);
    }
    /**
     * 发送自定义消息
     * */
    public static void sendInfo(TextMessage message, String userId) throws IOException {
        log.info("发送消息到:"+userId+"，报文:"+message);
        if(webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用户"+userId+",不在线！");
        }
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId=extractUserId(session);
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();

        }
        broadCastUserList();
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        onlineCount--;
    }
    public String extractUserId(WebSocketSession session){
        URI curUri=session.getUri();

        assert curUri != null;
        String[] uriItems=curUri.getPath().split("/");
        return uriItems[uriItems.length-1];
    }
    public void  broadCastUserList(){
        String userId="";
        try {
            //有新用户登陆后把用户列表进行广播
            SocketMessage msg=new SocketMessage();
            msg.setMsgType("UserList");
            msg.setSrcUserId("WebServer");
            msg.setDestUserId(userId);

            List<String> userList = new ArrayList<String>(webSocketMap.keySet()) ;
            msg.setOnlineList(userList);

            for (String key : webSocketMap.keySet()){
                TextMessage txtMsg= new TextMessage(JSON.toJSONString(msg));
                webSocketMap.get(key).sendMessage(txtMsg);
            }
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }
}
